package dao;

import model.News;
import util.JDBCUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    private JDBCUtil jdbcUtil;

    public NewsDao() throws SQLException {
        jdbcUtil = new JDBCUtil();
    }

    public List<News> getAllNews() {
        List<News> newsList = new ArrayList<>();
        try {
            String sql = "SELECT * FROM news";
            ResultSet resultSet = jdbcUtil.prepareQuery(sql);
            while (resultSet.next()) {
                News news = new News();
                news.setTitle(resultSet.getString("title"));
                news.setContent(resultSet.getString("content"));
                news.setAuthor(resultSet.getString("author"));
                news.setImagePath(resultSet.getString("image_Path"));
                newsList.add(news);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return newsList;
    }

    public boolean saveNews(String title,String author ,String content, String image_Path ) {
        try {
            String sql = "INSERT INTO news (title,author, content, image_Path) VALUES (?, ?, ?, ?)";
            PreparedStatement statement = jdbcUtil.prepareStatement(sql);
            statement.setString(1, title);
            statement.setString(2, author);
            statement.setString(3, content);
            statement.setString(4, image_Path);
            int rowsAffected = statement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
